package com.italicatab;

import java.util.ArrayList;
import java.util.HashMap;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlSerializer;

import com.androidquery.AQuery;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Product extends Activity implements OnClickListener {
	// All static variables
	static final String URL = "http://makemyonlineshop.com/demo/italica/api/v1/cate_list";
	static final String URL_PRODUCTS = "http://makemyonlineshop.com/demo/italica/api/v1/product_list_from_cateid/";
	String CAT_ID = "";
	// XML node keys
	static final String KEY_CATE_NAME = "maincategory"; // parent node
	static final String KEY_SUB_CATE_NAME = "category "; // parent node
	static final String KEY_ID = "id";
	ProgressBar PROGRESS_BAR;
	MyGridView MY_GRID;
	NetworkInfo nwinfo;
	ListView CAT_LIST;
	AQuery AQ;
	ImageView IV_APP_ICON, IV_CLOSE_DRAWER;
	RelativeLayout RL_DRAWER, RL_TOP_DRAWER;
	TextView TV_HEADER;
	ImageView IV_PRODUCTS, IV_ABOUT_US, IV_CONTACT_US, IV_HOME, IV_PROJECTS;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.product);
		init();
		AQ = new AQuery(Product.this);
		if (General.AllCategory != null && General.AllCategory.size() > 0) {
			CAT_LIST.setAdapter(new LazyAdapterList(Product.this));
			if (isOnline()) {
				General.AllProducts = new ArrayList<HashMap<String, String>>();
				new GetAllProducts().execute();
			} else {
				Toast.makeText(getApplicationContext(),
						"Please Check Internet connection", Toast.LENGTH_SHORT)
						.show();
			}
		} else {
			if (isOnline()) {
				General.AllCategory = new ArrayList<HashMap<String, String>>();
				new GetAllCategories().execute();
			} else {
				Toast.makeText(getApplicationContext(),
						"Please Check Internet connection", Toast.LENGTH_SHORT)
						.show();
			}

		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.gc();
	}

	private void init() {
		IV_PRODUCTS = (ImageView) findViewById(R.id.iv_product);
		IV_PRODUCTS.setOnClickListener(this);
		IV_ABOUT_US = (ImageView) findViewById(R.id.iv_about);
		IV_ABOUT_US.setOnClickListener(this);
		IV_CONTACT_US = (ImageView) findViewById(R.id.iv_contact);
		IV_CONTACT_US.setOnClickListener(this);
		IV_HOME = (ImageView) findViewById(R.id.iv_home);
		IV_HOME.setOnClickListener(this);
		IV_PROJECTS = (ImageView) findViewById(R.id.iv_projects);
		IV_PROJECTS.setOnClickListener(this);
		PROGRESS_BAR = (ProgressBar) findViewById(R.id.progressBar1);
		MY_GRID = (MyGridView) findViewById(R.id.myGridView1);

		PROGRESS_BAR.setVisibility(View.GONE);
		CAT_LIST = (ListView) findViewById(R.id.list_allcat);

		IV_APP_ICON = (ImageView) findViewById(R.id.iv_applogo);
		IV_APP_ICON.setOnClickListener(this);
		IV_CLOSE_DRAWER = (ImageView) findViewById(R.id.iv_close);
		IV_CLOSE_DRAWER.setOnClickListener(this);
		RL_DRAWER = (RelativeLayout) findViewById(R.id.lay_drawer);
		RL_TOP_DRAWER = (RelativeLayout) findViewById(R.id.rl_top_drawer);

		TV_HEADER = (TextView) findViewById(R.id.tv_header);

		MY_GRID.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (PROGRESS_BAR.getVisibility() == View.VISIBLE) {
					return;
				}
				Intent i = new Intent(getApplicationContext(),
						ProductDetail.class);
				i.putExtra("id",
						General.AllProducts.get(arg2).get("id_products"));
				startActivity(i);
				System.gc();
			}
		});

		CAT_LIST.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (PROGRESS_BAR.getVisibility() == View.VISIBLE) {
					return;
				}
				CAT_ID = General.AllCategory.get(arg2).get("id");
				TV_HEADER
						.setText(General.AllCategory.get(arg2).get("category"));
				General.AllProducts = new ArrayList<HashMap<String, String>>();
				RL_DRAWER.setVisibility(View.GONE);
				RL_TOP_DRAWER.setVisibility(View.GONE);
				IV_APP_ICON.setVisibility(View.VISIBLE);
				TV_HEADER.setVisibility(View.VISIBLE);
				new GetAllProducts().execute();
				System.gc();
			}
		});
	}

	public class GetAllCategories extends AsyncTask<Void, Integer, String> {
		String xml;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			PROGRESS_BAR.setVisibility(View.VISIBLE);
		}

		@Override
		protected String doInBackground(Void... params) {
			XMLParser parser = new XMLParser();
			xml = parser.getXmlFromUrl(URL); // getting XML
			// System.out.println(xml);

			Document doc = parser.getDomElement(xml); // getting DOM element
			doc.getDocumentElement().normalize();

			NodeList nl = doc.getElementsByTagName("Output");
			Node nfirst = nl.item(0);

			for (int i = 0; i < nfirst.getChildNodes().getLength(); i++) {

				// nodename should be category here (outer)
				Node nSec = nfirst.getChildNodes().item(i);
				// Log.e("magnum", "nSec chiclds name " + nSec.getNodeName());
				// //
				// category
				// category loop (outer)
				for (int j = 0; j < nSec.getChildNodes().getLength(); j++) {

					Node nThird = nSec.getChildNodes().item(j);

					String isNvalue = nThird.getFirstChild().getNodeValue();
					String isNode = nThird.getNodeName();
					if (isNvalue != null) {
						Element e = (Element) nThird;
						HashMap<String, String> map = new HashMap<String, String>();

						map.put("id", e.getAttribute("id"));
						map.put("thumbimage", e.getAttribute("thumbimage"));
						map.put("category", isNvalue);

						General.AllCategory.add(map);

					}
					if (isNode.equals("subcategory")) {

						for (int k = 0; k < nThird.getChildNodes().getLength() - 1; k++) {
							Node nFourth = nThird.getChildNodes().item(k);

							Element e = (Element) nFourth;
							HashMap<String, String> map = new HashMap<String, String>();

							map.put("id", e.getAttribute("id"));
							map.put("thumbimage", e.getAttribute("thumbimage"));
							map.put("category", nFourth.getFirstChild()
									.getNodeValue());

							General.AllCategory.add(map);

						}

					}

				}

			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			PROGRESS_BAR.setVisibility(View.GONE);
			CAT_LIST.setAdapter(new LazyAdapterList(Product.this));
			General.AllProducts = new ArrayList<HashMap<String, String>>();
			new GetAllProducts().execute();
		}

	}

	public class GetAllProducts extends AsyncTask<Void, Integer, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			PROGRESS_BAR.setVisibility(View.VISIBLE);
		}

		@Override
		protected String doInBackground(Void... params) {
			XMLParser parser = new XMLParser();
			String xml = parser.getXmlFromUrl(URL_PRODUCTS + CAT_ID); // getting
			// XML
			// Log.e("magnum", "product data is"+xml);
			Document doc = parser.getDomElement(xml); // getting DOM element
			doc.getDocumentElement().normalize();

			NodeList nl = doc.getElementsByTagName("product");
			// looping through all item nodes <item>
			for (int i = 0; i < nl.getLength(); i++) {
				// creating new HashMap
				HashMap<String, String> map = new HashMap<String, String>();
				Element e = (Element) nl.item(i);

				// adding each child node to HashMap key => value

				map.put("id_products", parser.getValue(e, "id_products"));
				map.put("productname", parser.getValue(e, "productname"));
				map.put("description", parser.getValue(e, "description"));
				map.put("categoryname", parser.getValue(e, "categoryname"));
				map.put("src", parser.getValue(e, "src"));
				// NodeList nl1 = e.getElementsByTagName("images");
				// System.out.println("node 0 " + nl1.item(0).getNodeName());
				//
				// if (nl1.item(0).getNodeName().equalsIgnoreCase("images")) {
				//
				// for (int k = 0; k < nl1.item(0).ge.getLength(); k++) {
				// Node nFourth = nl1.item(0).getChildNodes().item(k);
				//
				// Element e1 = (Element) nFourth;
				// if (e1.getAttribute("ismainimage")
				// .equalsIgnoreCase("1")) {
				// System.out.println("url "+nFourth.getNodeValue());
				// System.out.println("url 1 "+e1.getAttribute("src"));
				//
				// map.put("src", e1.getAttribute("src"));
				// }
				//
				// }

				// adding HashList to ArrayList
				General.AllProducts.add(map);
				// }
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			PROGRESS_BAR.setVisibility(View.GONE);
			MY_GRID.setAdapter(new LazyAdapterGrid(Product.this));

		}
	}

	public class LazyAdapterList extends BaseAdapter {
		// it is a custom adapter by this we are showing driver login
		// information as a list
		private Activity activity;
		private String[] data;
		private LayoutInflater inflater = null;

		// public ImageLoader imageLoader;

		public LazyAdapterList(Activity a) {
			activity = a;
			// data = d; //its image path
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// imageLoader = new ImageLoader(activity.getApplicationContext());
		}

		public int getCount() {
			return General.AllCategory.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// View vi = convertView;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.raw_cat_list, parent,
						false);
			}

			ImageView iv = (ImageView) convertView
					.findViewById(R.id.iv_cat_img);
			final TextView tv_name = (TextView) convertView
					.findViewById(R.id.tv_cat_name);

			String cat = General.AllCategory.get(position).get("category");
			tv_name.setText(cat);
			AQ.id(iv)
					.image(General.AllCategory.get(position).get("thumbimage"));

			return convertView;
		}

	}

	public class LazyAdapterGrid extends BaseAdapter {
		// it is a custom adapter by this we are showing driver login
		// information as a list
		private Activity activity;
		private String[] data;
		private LayoutInflater inflater = null;

		// public ImageLoader imageLoader;

		public LazyAdapterGrid(Activity a) {
			activity = a;
			// data = d; //its image path
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// imageLoader = new ImageLoader(activity.getApplicationContext());
		}

		public int getCount() {
			return General.AllProducts.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// View vi = convertView;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.raw_product, parent,
						false);
			}

			ImageView iv = (ImageView) convertView.findViewById(R.id.iv_one);
			TextView tv_name = (TextView) convertView
					.findViewById(R.id.tv_tile_name);

			String cat = General.AllProducts.get(position).get("productname");
			tv_name.setText(cat);
			String url = General.AllProducts.get(position).get("src");
			// System.out.println(url);
			clsLazyLoad lazy = new clsLazyLoad(Product.this, true);
			iv.setTag(url);
			lazy.DisplayImage(url, Product.this, iv);
			// AQ.id(iv).image(url);

			return convertView;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private boolean isOnline() {

		// it provides Internet information
		ConnectivityManager conmanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		nwinfo = conmanager.getActiveNetworkInfo();
		return nwinfo != null;
	}

	@Override
	public void onClick(View v) {
		if (PROGRESS_BAR.getVisibility() == View.VISIBLE) {
			return;
		}
		if (v == IV_APP_ICON) {
			RL_DRAWER.setVisibility(View.VISIBLE);
			RL_TOP_DRAWER.setVisibility(View.VISIBLE);
			IV_APP_ICON.setVisibility(View.GONE);
			TV_HEADER.setVisibility(View.GONE);
		} else if (v == IV_CLOSE_DRAWER) {
			RL_DRAWER.setVisibility(View.GONE);
			RL_TOP_DRAWER.setVisibility(View.GONE);
			IV_APP_ICON.setVisibility(View.VISIBLE);
			TV_HEADER.setVisibility(View.VISIBLE);

		} else if (v == IV_ABOUT_US) {
			Intent i = new Intent(getApplicationContext(), AboutUs.class);
			startActivity(i);
			finish();
		} else if (v == IV_CONTACT_US) {
			Intent i = new Intent(getApplicationContext(), ContactUs.class);
			startActivity(i);
			finish();
		} else if (v == IV_HOME) {
			Intent i = new Intent(getApplicationContext(), HomeScreen.class);
			startActivity(i);
			finish();
		} else if (v == IV_PROJECTS) {
			Intent i = new Intent(getApplicationContext(), Projects.class);
			startActivity(i);
			finish();
		}

	}

}
